/*
 * @Author: your name
 * @Date: 2020-11-22 14:48:20
 * @LastEditTime: 2020-12-05 21:22:19
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \wechat-server\src\middlewares\hotListTimer.js
 */
import axios from "axios";
import { hotList, topicList } from "../config/urlConfig";
import fs from "fs";
import * as cheerio from "cheerio";
import { setInterval } from "timers";
const fetchItems = () => {
  let headers = {
    "User-Agent":
      "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36",
    "Accept-Language": "en-US,en;q=0.5",
    "WeiboData-Type": "application/x-www-form-urlencoded",
    Connection: "Keep-Alive",
    // cookie: cookies.toString(),
  };
  let hotItems = [];
  let topicItems = [];
  axios(hotList, { headers })
    .then((res) => res.data)
    .then((body) => {
      const $ = cheerio.load(body);

      $(".data table tbody tr").each((index, el) => {
        const title = $(el).find(".td-02");
        let aTag = title.find("a");
        let titleText = aTag.text();
        let titleUrl = aTag.attr("href");
        titleUrl = titleUrl ? `https://s.weibo.com${titleUrl}` : titleUrl;
        const star = title.find("span").text();
        let face = title.find("img").attr("src");
        face = face ? `https:${face}` : face;
        let pic = title.find("img").attr("src");
        pic = pic ? `https:${pic}` : pic;
        const hotDes = $(el).find(".td-03").find("i").text();

        // 存 数据库
        // 没有数据库存成一个json文件 fs
        hotItems.push({
          titleText,
          titleUrl,
          face,
          star,
          pic,
          hotDes,
        });
      });
      fs.writeFile("./hotItems.json", JSON.stringify(hotItems), function (err) {
        if (!err) {
          console.log("文件写入完毕");
        }
      });
    });
  axios(topicList, {
    headers: {
      ...headers,
      "User-Agent":
        "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15",
    },
  })
    .then((res) => res.data)
    .then((body) => {
      const $ = cheerio.load(body);

      $(".list .list_b li").each((index, el) => {
        const img = "https:" + $(el).find("img").attr("src");
        const title = $(el).find("h2").text();
        const desc = $(el).find("p").text();
        const info = $(el).find("span").text();
        topicItems.push({
          img,
          title,
          desc,
          info,
        });
      });
      fs.writeFile(
        "./topicItems.json",
        JSON.stringify(topicItems),
        function (err) {
          if (!err) {
            console.log("文件写入完毕");
          }
        }
      );
    });
};

const timer = () => {
  fetchItems();
  setInterval(fetchItems, 1000 * 60);
};
export default timer;
